<template>
    <div class="store-record-main">
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item prop="keyword" label="兑换人">
                            <el-input
                                v-model.trim="form.keyword"
                                clearable
                                placeholder="输入兑换人的昵称或手机号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item prop="goodsName" label="商品名称">
                            <el-input
                                v-model.trim="form.goodsName"
                                clearable
                                placeholder="输入兑换的商品名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="zw-form-btns">
                        <div>
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                            <el-button plain @click="resetHandler">清空</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-table :data="tableList" style="margin-top: 20px">
            <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                <template #default="{ row }">
                    <div v-if="prop === 'operations'">
                        <el-button size="small" @click="handleRouter(row)">查看订单</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div style="margin-top: 15px">
            <Pagination
                :total="totalCount"
                :page-size="form.perPage"
                :current-page="form.page"
                @sizeChange="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
    </div>
</template>

<script setup>
import { onUnmounted, onMounted, reactive, ref, unref } from 'vue';
import request from '@/request/index';
import Pagination from '@/components/Pagination.vue';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();

const form = reactive({
    page: 1,
    perPage: 10,
    keyword: '', // 兑换人昵称或手机号
    goodsName: '' // 商品名称
});
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = reactive([
    { label: '兑换人', prop: 'nicknameText', width: '200', showOverflowTooltip: true },
    { label: '商品类型', prop: 'goodsTypeName' },
    { label: '商品名称', prop: 'goodsName', minWidth: '200', showOverflowTooltip: true },
    { label: '兑换价', prop: 'pointsText', minWidth: '170' }, // todo:兑换价格
    { label: '兑换数量', prop: 'goodsCount' }, // todo:兑换数量
    { label: '来源店铺', prop: 'shopNameText', minWidth: '120', showOverflowTooltip: true },
    { label: '兑换时间', prop: 'createdAt', width: '170' },
    { label: '操作', prop: 'operations', width: '150', fixed: 'right' }
]);

const handleRouter = row => {
    const { href } = router.resolve({
        path: '/order/list/detail',
        query: {
            orderId: row.orderId,
            shopId: row.shopId
        }
    });
    window.open(href, '_blank');
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};

/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};

const queryCouponListHandler = async () => {
    const { data } = await request('pointsExchange', form);
    tableList.length = 0;
    const goodTypes = ['商城商品', '优惠券', '抽奖机会'];
    Object.assign(
        tableList,
        (data?.list || []).map(item => {
            const { orderGoods = [], buyer = {}, ...rest } = item;
            const orderGoodsCopy = (orderGoods || [])[0] || {};
            const { points } = orderGoodsCopy;
            item.goodsTypeName = goodTypes[orderGoodsCopy?.goodsType - 1];
            if (item.orderAmountTotal !== null || points) {
                if (item.orderAmountTotal && points) {
                    item.pointsText = `${item.orderAmountTotal / 100}元+${points / 100}积分`;
                } else {
                    if (item.orderAmountTotal) {
                        item.pointsText = `${item.orderAmountTotal / 100}元`;
                    } else if (points) {
                        item.pointsText = `${points / 100}积分`;
                    } else {
                        item.pointsText = '-';
                    }
                }
            }
            const buyerInfo = buyer || {};
            if (buyerInfo?.nickname && buyerInfo?.buyerMobile) {
                item.nicknameText = `${buyerInfo.nickname}（${buyerInfo.buyerMobile}）`;
            } else {
                item.nicknameText = buyerInfo?.nickname || buyerInfo?.buyerMobile || '';
            }
            item.shopNameText = item?.shopName?.shopName;
            return { ...orderGoodsCopy, ...item, ...rest, ...buyer };
        })
    );
    totalCount.value = data?.totalCount;
};

onMounted(() => {
    queryCouponListHandler();
});
onUnmounted(() => {});
</script>

<style lang="scss" scoped>
.store-record-main {
    .store-header {
        background: #fffaf9;
        border: 1px solid #facaa8;
        display: flex;
        align-items: center;
        height: 48px;
        padding-left: 16px;
        margin-bottom: 20px;
    }
    .form-footer {
        position: absolute;
        bottom: 0;
        left: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% - 200px);
        height: 70px;
        background-color: #fff;
        .el-button {
            width: 80px;
        }
    }
    .custom-goods-name {
        display: inline-flex;
        align-items: center;
        width: 100%;
        &-span {
            display: -webkit-box;
            max-width: calc(100% - 45px);
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }
    }

    .custom-number-small {
        width: 80px;
        margin: 0 4px;
    }

    .custom-number-small-box {
        &:not(:first-of-type) {
            margin-top: 10px;
        }
    }

    .custom-switch {
        margin-left: 5px;
    }
}
</style>
